<template>
	<view class="storecart skinStyle1">
		<view class="com-top" v-if="cartList.length>0">
			<view class="left-text">购物车共<text class="red">{{cartCount}}</text>件商品</view>
			<view class="com-top-right" @click="editCart">
				<i class="line"></i>
				<text class="cart-text">{{delBtnFlag?'完成':'编辑'}}</text>
			</view>
		</view>

		<mescroll-body ref="mescrollRef" top="80" @init="mescrollInit" @down="downCallback" :up="upOption" 
		@up="getPointsCart">
			
			<view class="tui-cart-cell" v-for="(item, index) in cartList" :key="index" :id="'item'+item.id">
				<tui-swipe-action :actions="actions" @click="handlerButton" :params="item" class="swipe-action">
					<template v-slot:content>
						<view class="tui-goods-item-wrap">
							<view v-if="item.goodsStock>0" class="check-box-wrap" @tap="selectSingle(item,index)">
								<view class="check-box" :class="item.checked?'select':''">
									<view class="iconfont iconduihao" v-if="item.checked"></view>
								</view>
							</view>
							<view v-else class="check-box-wrap">
								
							</view>
							<view class="tui-goods-item" @tap="goGoodsDetail(item)">
								<view class="tui-goods-img">
									<image :src="imgSrc + item.imgRelativeUri" />
								</view>
								<view class="tui-goods-info">
									<view class="tui-goods-info-inner">
										<view class="tui-goods-title">{{ item.goodsName }}</view>
										<view class="tui-goods-sub">
											<template v-if="item.goodsStock>0">
												剩余库存：{{item.goodsStock}}
												<text style="display: inline-block;margin-left: 20rpx;" v-if="item.goodsNumber">限购：{{item.goodsNumber}}</text>
											</template>
											<template v-else>
												抢光了
											</template>
										</view>
										<view class="tui-price-box">
											<view class="tui-goods-price">{{item.goodPoints}} <text class="small-size">积分</text></view>
											<view class="tui-goods-num" @tap.stop="numberFn($event)">
												<tui-numberbox :value="item.goodsQty" :height="38" :width="70" :min="1"
												:index="index" :max="item.goodsNumber?item.goodsNumber:item.goodsStock" @change="changeNum($event, item, index)"></tui-numberbox>
											</view>
										</view>
									</view>
								</view>
							</view>
						</view>
					</template>
				</tui-swipe-action>
			</view>
			<view class="safe-area"></view>
		</mescroll-body>
	
		<view class="tui-tabbar" v-if="cartList.length>0">
			<view>
				<view class="check-box-wrap check-all" @tap="selectAll" v-if="cartList.length>0">
					<view class="check-box" :class="allChecked?'select':''">
						<view class="iconfont iconduihao" v-if="allChecked"></view>
					</view>
				</view>
				<view class="tui-total-price">
					<view class="use">合计：{{usePoints}}<text class="small-size">积分</text></view>
					<view class="surplus">剩余积分：{{surplus}}</view>
				</view>
			</view>
			
			<view class="storecart-btn">
				<tui-button v-if="delBtnFlag" width="180rpx" height="70rpx" :size="30" type="black" shape="circle" @tap="deleteClick"
				 :disabled="cartList.length===0||!someSelectedFlag" :plain="true">删除</tui-button>
				<tui-button v-else width="180rpx" height="70rpx" :size="30" type="danger" shape="circle" @tap="btnPay" :disabled="cartList.length===0||!usePoints">结算</tui-button>
			</view>
		</view>

		<mix-empty v-if="cartList.length===0" :type="'default'" :backgroundColor="'#fff'"></mix-empty>
		<tui-modal></tui-modal>
		<loading></loading>
	</view>
</template>
<script>
	import mixEmpty from '@/components/mix-empty/mix-empty.vue'
	import tuiSwipeAction from '@/components/swipe-action/swipe-action';
	import tuiButton from '@/components/button/button';
	import tuiNumberbox from '@/components/numberbox/numberbox';
	import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins.js";
	export default {
		mixins: [MescrollMixin],
		components: {
			mixEmpty,
			tuiSwipeAction,
			tuiButton,
			tuiNumberbox
		},

		data() {
			return {
				cartList: [],
				imgSrc: this.$store.state.imgUrl,
				delBtnFlag: false,
				allChecked: false,
				actions: [{
					name: '删除',
					color: '#fff',
					fontsize: 30, //单位rpx
					width: 70, //单位px
					background: '#EA655E'
				}],
				isLoading: false,
				upOption: {
					page: {
						size: 10 // 每页数据的数量,默认10
					},
					noMoreSize: 10,
				},
				totalPoints: uni.getStorageSync('agencyPoints'),
				usePoints: 0,
				surplus: 0, //剩余积分
				from:'agent',
				cartCount:0,
				refreshFlg: false,
				someSelectedFlag:false,//是否有个商品被选中，用来判断删除按钮是否可点击
			};
		},
		onLoad(options) {
			// #ifdef H5
			   this.$wechat.noShare();
			// #endif
			// 监听页面刷新
			// this.$eventHub.$off('refreshPointsCart');
			this.$eventHub.$on('refreshPointsCart', () => {
			   this.refreshFlg = true;
			});
		},
		onShow(){
			if (this.refreshFlg) {
				this.refreshFlg = false;
				this.mescroll.resetUpScroll()
			}
			
		},
		methods: {
			getPointsCart(page) {
				this.allChecked=false;
				this.getUsePoints();
				this.getDealerCartCount();//购物车件数
				this.$http.pointsDealerCart().then((res) => {
					if (res.status === 0) {
						
						let curPageData = res.data;
						res.data.forEach(item=>{
							item.checked=false;
						})
						this.mescroll.endSuccess(res.data.length);
						if (page.num == 1) {
							this.cartList = []
						};
						this.cartList = this.cartList.concat(curPageData);
					}
				})
			},
			getDealerCartCount() {
				this.$http.getDealerCartCount().then((res) => {
					if (res.status === 0) {
						this.cartCount=res.data;
					}
				})
			},
			numberFn(e) {
				e.preventDefault();
			},
			getSurplusPoints(){
				this.usePoints = 0;
				this.cartList.forEach((item, index) => {
					if (item.checked) {
						this.usePoints += Number(item.goodPoints) * item.goodsQty;
					}
				});
				let surplus = (this.totalPoints - this.usePoints).toFixed(0);
				return Number(surplus);
			},
			//改变购买数量
			changeNum(e, item,index) {
				if(item.checked&&!this.delBtnFlag){//选中的状态并且不在编辑中改变数量
					let surplus=0
					this.usePoints = 0;
					this.cartList.forEach((childItem,childIndex) => {
						if (childItem.checked&&childIndex==index) {
							this.usePoints += Number(childItem.goodPoints) * e.value;
						}else if (childItem.checked&&childIndex!==index){
							this.usePoints += Number(childItem.goodPoints) * childItem.goodsQty;
						}
					});
					surplus = (this.totalPoints - this.usePoints).toFixed(0);
					if(surplus>=0){
						this.surplus = surplus;
						this.changeNumSure(e, item);
					}else{
						
						item.goodsQty = e.value;
						item.checked=false;
						this.allChecked=false;
						this.surplus=this.getSurplusPoints();
						uni.showToast({
							title:'剩余积分不足',
							icon:'none',
						})
					}
					
				}else{
					this.changeNumSure(e, item)
				}
			},
			changeNumSure(e, item){
				item.goodsQty = e.value;
				let data={
					updateInfo:[{
						goodsId: item.goodsId,
						goodsQty:e.value
					}]
				}
				this.$http.editPointCart(data).then((res) => {
					if(res.status == 0) {
						this.getDealerCartCount();
					}
				})
			},
			//计算已使用的积分
			getUsePoints() {
				this.usePoints = 0;
				this.cartList.forEach((item, index) => {
					if (item.checked) {
						this.usePoints += item.goodPoints * item.goodsQty;
					}
				});
				let surplus = (this.totalPoints - this.usePoints).toFixed(0);
				if(surplus>=0){
					this.surplus = surplus;
				}else{
					uni.showToast({
						title:'剩余积分不足',
						icon:'none',
					})
					return;
				}
			},
			handlerButton(e) {
				//删除单个商品
				const ids = [];
				ids.push(e.item.id);
				this.deleteCommon(ids)
			},
			deleteClick() {
				let ids = [];
				//删除那些选择的
				this.cartList.forEach((item, index) => {
					if (item.checked) {
						ids.push(item.id);
					}
				});
				this.deleteCommon(ids)
				this.someSelectedFlag=false;
			},
			deleteCommon(ids){
				let data={
					ids:ids
				}
				this.$http.editPointCart(data).then((res) => {
					if(res.status == 0) {
						uni.showToast({
							icon:'none',
							title:'删除成功'
						})
						this.cartList = [];
						this.mescroll.resetUpScroll();
						//更新购物车件数
						this.getDealerCartCount();
						this.getUsePoints();
						this.allChecked=false;
					}
				})
			},
			editCart() {
				this.delBtnFlag = !this.delBtnFlag;
			},

			viewCodesModal(list) {
				this.codeFlag = true
				this.codeList = list;
			},
			hideCodesModal() {
				this.codeFlag = false
			},
			// 结算
			btnPay() {
				let selectedList = [];
				this.cartList.forEach(item => {
					if (item.checked) {
						selectedList.push({
							goodsId: item.goodsId,
							goodsQty: item.goodsQty
						})
					}
				})
				
				uni.navigateTo({
					url: `/packageD/pages/pointsOrder/settleOrderDetail?from=${this.from}&pageName=pointsCart&goodsInfo=${JSON.stringify(selectedList)}`
				});
			},

			// 单个商品的选择
			selectSingle(item,index) {
				let that=this;
				item.checked = !item.checked
				if (!item.checked) {//要不选中
					that.allChecked = false
					if(!that.delBtnFlag){
						that.surplus=this.getSurplusPoints()
					}
					this.someSelectedFlag=false;
					for(let i=0;i<this.cartList.length;i++){
						if(this.cartList[i].checked){
							this.someSelectedFlag=true;
						}
						break;
					}
				} else {//要选中
					this.someSelectedFlag=true;
					if(!that.delBtnFlag){
						let surplus=this.getSurplusPoints()
						if(surplus>=0){
							that.surplus = surplus;
							// 判断每一个商品是否是被选择的状态
							const cartList = that.cartList.every(item => {
								return item.checked === true
							})
							if (cartList) {
								that.allChecked = true
							} else {
								that.allChecked = false
							}
						}else{
							item.checked=false
							that.surplus=this.getSurplusPoints()
							uni.showToast({
								title:'剩余积分不足',
								icon:'none'
							})
							return;
						}
					}else{
						const cartList = that.cartList.every(item => {
							return item.checked === true
						})
						if (cartList) {
							that.allChecked = true
						} else {
							that.allChecked = false
						}
					}
				}
			},
			//全选、全不选
			selectAll() {
				if (!this.allChecked) {//要全选
					this.someSelectedFlag=true;
					if(!this.delBtnFlag){
						this.usePoints = 0;
						this.cartList.forEach((item, index) => {
							this.usePoints += Number(item.goodPoints) * item.goodsQty;
						});
						let surplus = (this.totalPoints - this.usePoints).toFixed(0);
						if(surplus>=0){//全选成功
							this.cartList.map(item => {
								item.checked = true
							})
							this.allChecked = !this.allChecked
							this.surplus = surplus;
						}else{//保持之前不变
							this.surplus=this.getSurplusPoints()
							uni.showToast({
								title:'剩余积分不足',
								icon:'none'
							})
							return;
						}
					}else{
						this.cartList.map(item => {
							item.checked = true
						})
						this.allChecked = !this.allChecked
					}
					
				} else {//不选择
					this.someSelectedFlag=false;
					this.allChecked = !this.allChecked
					this.cartList.map(item => {
						item.checked = false
					})
					if(!this.delBtnFlag){
						this.surplus = this.getSurplusPoints();
					}
				}
			},
			goGoodsDetail(item) {
				uni.navigateTo({
					url: `/packageD/pages/pointGoodsDetail/pointGoodsDetail?from=agent&id=${item.goodsId}`
				})
			},
		}
	};
</script>

<style lang="scss">
	@import "@/packageD/static/style/common.scss";

	.storecart {
		width: 100%;
		position: relative;
		// padding-bottom: calc(constant(safe-area-inset-bottom) + 136rpx);
		// padding-bottom: calc(env(safe-area-inset-bottom) + 136rpx);
		// overflow-y: auto;
		// padding-top: 76rpx;
		.com-top{}
		.safe-area{
			width: 100%;
			height: calc(constant(safe-area-inset-bottom) + 136rpx);
			height: calc(env(safe-area-inset-bottom) + 136rpx);
		}
		.tui-cart-cell {
			width: 100%;
			background: #ffffff;
			overflow: hidden;
			margin-top: 16rpx;

			.tui-goods-item-wrap {
				width: 100%;
				padding: 30rpx;
				display: flex;

				.tui-checkbox {
					width: 55rpx;
					display: flex;
					align-items: center;
					float: left;
					margin-right: 10rpx;
				}
			}
		}

		.tui-tabbar {
			width: 100%;
			height: calc(constant(safe-area-inset-bottom) + 120rpx);
			height: calc(env(safe-area-inset-bottom) + 120rpx);
			padding: 28rpx 32rpx;

			display: flex;
			justify-content: space-between;
			align-items: center;
			padding-bottom: calc(constant(safe-area-inset-bottom) + 30rpx);
			padding-bottom: calc(env(safe-area-inset-bottom) + 30rpx);

			.tui-checkbox {
				width: 60rpx;
			}

			.tui-total-price {
				padding-left: 60rpx;

				.use {
					color: $red;
					font-size: 32rpx;

					.small-size {
						font-size: 24rpx;
					}
				}

				.surplus {
					font-size: 24rpx;
				}
			}
		}
	}
	.check-box-wrap{
		width: 54rpx;
		height: 200rpx;
		display: flex;
		justify-content:left;
		align-items: center;
		.check-box {
			width: 32rpx;
			height:32rpx;
			background: #FFFFFF;
			border-radius: 8rpx;
			border: 2rpx solid #d1d1d1;
			line-height: 28rpx;
			.iconfont {
				font-size: 30rpx;
				color: #fff;
				display: inline-block;
				margin-left: -2rpx;
			}
		}
		.select{
			background-image:linear-gradient(to right,#F69E97,#EA655E) !important;
			width: 32rpx;
			height: 32rpx;
			border: 2rpx solid #F69E97;
		}
	}
	.check-all{
		height: 70rpx;
		float: left;
	}
	
	
	/deep/ .uni-scroll-view::-webkit-scrollbar {
		/* 隐藏滚动条，但依旧具备可以滚动的功能 */
		display: none;
	}
</style>
